package com.ajk.server.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.ajk.server.exception.AjkException;
import com.ajk.server.exception.ErrorConstant;
import com.ajk.server.model.request.UserReq;
import com.ajk.server.model.response.ResultObject;
import com.ajk.server.utils.FileStoreUtil;

/**
 * 
 * @author chenxuan
 *
 */
@Controller
@RequestMapping("/file")
public class FileController {

	@RequestMapping(value = "/upload", method = RequestMethod.POST,consumes="multipart/form-data")
	@ResponseBody
	public ResultObject<String> upload(MultipartFile file){
		
		ResultObject<String> result = new ResultObject<String>();
		if(file!=null && file.getSize()>0){
			if (file.getSize() > 2097152) {
				throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "文件太大,请选择小于2兆的文件上传");
			}
			String filePath = FileStoreUtil.storeFile(file, "upload");
			result.setDomain(FileStoreUtil.getBaseUrl()+filePath);
			result.setExt(filePath);
		} else {
			// 文件传输失败。抛异常
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "文件传输失败！请重试");
		}
		return result;
	}
	
	@RequestMapping(value = "/upload_url", method = RequestMethod.POST,consumes="multipart/form-data")
	public void uploadToString(MultipartFile file,HttpServletResponse response){
		
		String filePath = null;
		if(file!=null && file.getSize()>0){
			if (file.getSize() > 2097152) {
				throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "文件太大,请选择小于2兆的文件上传");
			}
			filePath = FileStoreUtil.storeFile(file, "upload");
			filePath=FileStoreUtil.getBaseUrl()+filePath;
		} else {
			// 文件传输失败。抛异常
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "文件传输失败！请重试");
		}
		try {
			response.getOutputStream().print(filePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}